const {SMSCode} = require('../model/smscode')
const moment = require('moment-timezone')
const fs= require('fs-extra')
const {postImg} = require('../model/postImg')
const {Topic} = require('../model/topics')
const {rootPath} = require('../utils/index')
const {Discussion} = require('../model/discussions')
const {Reply} = require('../model/reply')
const {getMaterialSrc} = require('../utils')
// let nowTime = moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss')
//定时删除验证码
let timmer1 = setInterval(async() => {
    let nowTime = moment().tz("Asia/Shanghai").format('YYYY/MM/DD HH:mm:ss')
    let datas = await SMSCode.find()
    if(datas.length!=0){
        //删除数据库创建时间对比当前超过了90秒的数据
        await SMSCode.remove({
            //日期比较靠后的时间戳更大
            createdAt:{
                $lte:moment(nowTime).subtract(91,'seconds').format('YYYY/MM/DD HH:mm:ss')
            }
        })
    }
}, 5000);
// console.log(moment(nowTime).subtract(91,'seconds').format('YYYY/MM/DD HH:mm:ss'))

//定时删除没有用上的图片的文档
let timmer2 = setInterval(async() => {
    //帖子与上传图片的列表
    const topic = await Topic.find()
    const postimages = await postImg.find()
    let imgArr = []
    //遍历上传图片列表并且存储ID
    //判断postimg里的图片是否为topic.image里面的图片,如果不是就删除
    let usefulImg =[]
    //遍历帖子列表以遍历帖子的图片组列表
    topic.forEach((item,index,array) => {
        item.images.forEach((v,i,arr) => {
            usefulImg.push(v.toString())
        })
    })
    let discussions = await Discussion.find()
    discussions:await Promise.all(discussions.map(async(item) => {
        let imgReg = /<img.*?(?:>|\/>)/gi //匹配图片中的img标签
        let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i // 匹配图片中的src
        let srcArr = []
        let str = item.content
        let arr = str.match(imgReg)  //筛选出所有的img
        // console.log(arr)
        if(arr) {
            for (let i = 0; i < arr.length; i++) {
                let src = arr[i].match(srcReg)
                // 获取图片地址
                srcArr.push(src[1])
            }
        }
        srcArr:await Promise.all(srcArr.map(async(v,i,arr)=>{
            let nameStr = v.replace(/^https?:\/\/[^\/]*/mg,'')
            nameArr = nameStr.split('/')
            if(nameArr.length==4){
                let imgdoc = await postImg.find({name:nameArr[3]})
                if(imgdoc.length>0){
                    let imgId = imgdoc[0]._id
                    usefulImg.push(imgId.toString())
                }
            }
            return v
        }))
        return item
    }))
    let relies = await Reply.find()
    relies:await Promise.all(relies.map(async (item) => {
        let imgReg = /<img.*?(?:>|\/>)/gi //匹配图片中的img标签
        let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i // 匹配图片中的src
        let srcArr = []
        let str = item.content
        let arr = str.match(imgReg)  //筛选出所有的img
        if(arr) {
            for (let i = 0; i < arr.length; i++) {
                let src = arr[i].match(srcReg)
                // 获取图片地址
                srcArr.push(src[1])
            }
        }
        srcArr:await Promise.all(srcArr.map(async(v,i,arr)=>{
            let nameStr = v.replace(/^https?:\/\/[^\/]*/mg,'')
            nameArr = nameStr.split('/')
            if(nameArr.length==4){
                let imgdoc = await postImg.find({name:nameArr[3]})
                if(imgdoc.length>0){
                    let imgId = imgdoc[0]._id
                    usefulImg.push(imgId.toString())
                }
            }
            return v
        }))
        return item
    }))
    postimages.forEach(async(item,index,array)=>{
        if(usefulImg.includes(item._id.toString())==false){
            let img = await postImg.findById(item.id)
            if(await fs.pathExists(rootPath+'/public'+img.url)){
                await fs.remove(rootPath+'/public'+img.url,err=>{
                    if (err) return console.error(err)
                    console.log('remove success!'+img.url)
                })
            } else if(await fs.pathExists(rootPath+'public/'+img.user+'/'+img.url)) {
                await fs.remove(rootPath+'public/'+img.user+'/'+img.url,err=>{
                    if (err) return console.error(err)
                    console.log('remove success!'+img.url)
                })
            } else {
                console.log("no img")
            }
            await postImg.findByIdAndRemove(item.id)
        }
    })
}, 3600000);
module.exports={
    // timmer1
}